﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PhotoGalleryEnteties;

namespace PhotogalleryModel
{
    public class CommentRepository
    {
        private IContext _context;

        public CommentRepository (ModelContext  context)
        {
            _context = context.Context ;
        }

        public PhotoComment CreateComment()
        {
            PhotoComment comment = _context.CreateObject<PhotoComment>();
            comment.AdditionDate = DateTime.Now;
            return comment;
        }

        public void DeleteComment(int commentId)
        {
            PhotoComment comment = _context.PhotoComments.Where(p => p.CommentId == commentId).FirstOrDefault();
            if (comment == null)
                throw new GalleryModelException(String.Format("Comment with id {0} doesn`t exist", commentId));
            DeleteComment(comment);
        }

        public void DeleteComment(PhotoComment comment)
        {
            if (comment == null)
                throw new ArgumentNullException();
            _context.DeleteObject(comment);
        }

        public ICollection< ValidationError > ValidateComment(PhotoComment comment)
        {
            List<ValidationError> errors = new List<ValidationError>();

            if(comment.Author ==null)
            {
                errors.Add(new ValidationError() {ErrorTag = "Author",ErrorMessage = "Comment should have author"});
            }
            if(comment.Photo ==null)
            {
                errors.Add(new ValidationError()
                               {ErrorTag = "Photo", ErrorMessage = "Comment should be assosiated with Photo"});
            }
            if(string.IsNullOrWhiteSpace(  comment.Comment) )
            {
                errors.Add(new ValidationError() {ErrorTag = "Comment", ErrorMessage = "empty comment body"});
            }

      
            return errors;

        }

        #region SelectMethods 

        public IEnumerable< PhotoComment > GetPhotoComments(int photoId)
        {
            PhotoInfo photo = _context.Photos.Where(p => p.PhotoId == photoId).FirstOrDefault();
            if (photo == null)
                throw new GalleryModelException(string.Format("Photo with id {0} doesn`t exist",photoId ));
            return  photo.PhotoComments;
        }

        public IEnumerable <PhotoComment > GetRootComments(int photoId)
        {
            return GetPhotoComments(photoId).Where(p => p.ParentComment == null);
        }

        public PhotoComment GetComment(int id)
        {
            PhotoComment comment = _context.PhotoComments.Where(p => p.CommentId == id).FirstOrDefault();
            if(comment==null )
                throw new GalleryModelException(String.Format("Comment with id {0} doesnt` exist", id));

            return comment;
        }

        #endregion 
    }
}
